import os
import io
import errno
import nest_asyncio
from tornado.httpclient import  HTTPClient, HTTPRequest

class RequestRepoRawFile:
        
    def wgetFile(self, repo, branch, path):
        """
        Wget repository single file from code repository raw page
        path: lab/tree/markdown-editor/code123/index.ipynb
        """
        file_store_dir = 'tmp/'
        namespace_path, repo_path = repo.rsplit('/', 1)
        if path.startswith('lab/tree/'):
            # lab
            service = 'lab/tree/'
            repo_file_path = path.replace('lab/tree/', '', 1)
            repo_file_path = repo_file_path.replace(repo_path + '/', '', 1)
        else:
            # notebook
            service = 'tree/'
            repo_file_path = path.replace('tree/', '', 1)
            repo_file_path = repo_file_path.replace(repo_path + '/', '', 1)
        repo_file_store_path = file_store_dir + repo_path + '/' + repo_file_path
        file_url = "%s/-/raw/%s/%s" % (repo, branch, repo_file_path)
        # repo_file_store_dir, file_name = repo_file_store_path.rsplit("/", 1)
        repo_file_store_dir, file_name = repo_file_store_path.rsplit("/", 1)
        # print(">", "mkdir " + repo_file_store_dir)
        # if not os.path.exists(repo_file_store_dir):
        #     try:
        #         os.makedirs(repo_file_store_dir, 0o755)
        #     except OSError as e:
        #         print(e)
        #         if e.errno != errno.EEXIST:
        #             raise

        print(">", "wget " + file_url)
        file_content = self.wget(file_url)
        file_content = file_content.decode('utf8', 'replace')
        with io.open(file_name, 'w', encoding='utf-8') as f:
            f.write(file_content)
        return service + file_name
    
    def wget(self, url):
        """
        get file content from a certain url
        """
        nest_asyncio.apply()
        req = HTTPRequest(
            url,
            method="GET",
            headers={
                "Accept": "application/json",
                "User-Agent": "CSDN JupyterHub"
            }
        )
        response = HTTPClient().fetch(req)
        return response.body

